import { createRouter, createWebHashHistory } from "vue-router";
import { getCookie } from "../utils/auth.js";
import { toast } from "../utils/index.js";
import { useAdminStore } from "../stores/admin.js";
import pinia from "@/stores/index.js";

// 进度条
import nprogress from "nprogress";
import "nprogress/nprogress.css";
const store = useAdminStore(pinia);
// 基础路由
const routes = [
  {
    path: "/",
    // redirect: "/admin",
    name: "admin",
    component: () => import("../views/layout/Layout.vue"),
    children: [
      {
        path: "/",
        // meta: {
        //   title: "主控台",
        // },
        component: () => import("../views/second/shop_coupon_list.vue"),
      },
    ],
  },
  {
    path: "/login",
    meta: {
      title: "登录",
    },
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    component: () => import("../views/Notfound.vue"),
  },
];

function generateAsyncRoutes(menus) {
  console.log(menus);
  // menus arr
  let hasNewsR = false;
  function mapRoute(menus) {
    menus.forEach((arr) => {
      // 一级菜单 frontpath
      const hasR = asyncRoutes.find((asycnRoute) => {
        return asycnRoute.path === arr.frontpath;
      });
      // 如果该frontpath 没有存在router路由表中，但是呢，异步路由中又包含他
      if (hasR && !router.hasRoute(arr.frontpath)) {
        router.addRoute("admin", hasR);
        hasNewsR = true;
      }
      if (arr.child && arr.child.length > 0) {
        // 再次遍历子路由路由
        mapRoute(arr.child);
      }
    });
  }

  mapRoute(menus);

  // menus.forEach((item) => {
  //   // item 一级菜单

  //   if (item.child && item.child.length > 0) {
  //     item.child.forEach((childItem) => {
  //       // childItem 子菜单
  //       // 判断路由是否存在？
  //       router.addRoute({
  //         path: "",
  //         meta: {},
  //         name: "",
  //         // component:()=>import("../views" + childItem.frontpath + ".vuew")
  //         component: () => import("../views" + /goods/list + ".vuew"),
  //       });
  //     });
  //   }
  //   // 1. 如何避免重复的添加路由？
  //   // 2. 刷新后路由实效？
  // });
  return hasNewsR;
}

const asyncRoutes = [
  {
    path: "/",
    name: "/",
    meta: {
      title: "主控台",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/goods/list",
    name: "/goods/list",
    meta: {
      title: "商品管理",
    },
    component: () => import("../views/second/GoodsList.vue"),
  },
  {
    path: "/category/list",
    name: "/category/list",
    meta: {
      title: "分类管理",
    },
    component: () => import("../views/second/CategoryList.vue"),
  },
  {
    path: "/skus/list",
    name: "/skus/list",
    meta: {
      title: "规格管理",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/coupon/list",
    name: "/coupon/list",
    meta: {
      title: "优惠券管理",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/user/list",
    name: "/user/list",
    meta: {
      title: "用户管理",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/level/list",
    name: "/level/list",
    meta: {
      title: "会员等级",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/order/list",
    name: "/order/list",
    meta: {
      title: "订单管理",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/comment/list",
    name: "/comment/list",
    meta: {
      title: "评论管理",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/manager/list",
    name: "/manager/list",
    meta: {
      title: "管理员管理",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/access/list",
    name: "/access/list",
    meta: {
      title: "权限管理",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/role/list",
    name: "/role/list",
    meta: {
      title: "角色管理",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/setting/base",
    name: "/setting/base",
    meta: {
      title: "基础设置",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/setting/buy",
    name: "/setting/buy",
    meta: {
      title: "交易设置",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/setting/ship",
    name: "/setting/ship",
    meta: {
      title: "物流设置",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/distribution/index",
    name: "/distribution/index",
    meta: {
      title: "分销员管理",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/distribution/setting",
    name: "/distribution/setting",
    meta: {
      title: "分销设置",
    },
    component: () => import("../views/Home.vue"),
  },
  {
    path: "/image/list",
    name: "/image/list",
    meta: {
      title: "图库管理",
    },
    component: () => import("../views/ImageList/index.vue"),
  },
  {
    path: "/notice/list",
    name: "/notice/list",
    meta: {
      title: "公告管理",
    },
    component: () => import("../views/Home.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});
let isGetAdminInfo = false;
// 路由前置守卫的配置
router.beforeEach(async (to, from, next) => {
  nprogress.start();
  if (to.meta) {
    document.title = to.meta.title + "-后台管理系统";
  }
  const token = getCookie();
  // 如果想去的页面不是login且token没有，则弹出提示框，并且跳转到登录页
  if (!token && to.path !== "/login") {
    toast("请先登录", "error");
    return next("/login");
  }
  if (token && to.path == "/login") {
    // 如果有token和想去的页面是login，弹出提示框，然后回到首页
    toast("你已登录，请勿重新登录", "error");
    return next({
      path: from.path ? from.path : "/",
    });
  }
  let hasNewsR = false;

  if (token && !isGetAdminInfo) {
    await store.getAdminInfo();
    console.log(store.adminInfo, "----------------");
    isGetAdminInfo = true;
    hasNewsR = generateAsyncRoutes(store.adminInfo.menus);
  }
  // next();
  hasNewsR ? next(to.fullPath) : next();
});
router.afterEach((to, from) => {
  nprogress.done();
});
export default router;
